package com.qinglian.utils;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * @Description:  指定缓存过期时间
     * @Param: [key 键, time单位 秒]
     * @return:布尔值
    com.laiYongBin.util.RedisTempUtil
     */
    public boolean expire(String key,long time){
        try{
            if (time>0){
                redisTemplate.expire(key,time,TimeUnit.SECONDS);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description:  获取键的过期时间
     * @Param: [key]
    com.laiYongBin.util.RedisTempUtil
     */
    public Long getExpire(String key){
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }

    /**
     * @Description: 判断key是否存在
     * @Param: key:键
     * @return:布尔值
    com.laiYongBin.util.RedisTempUtil
     */
    public boolean hasKey(String key){
        try {
            return redisTemplate.hasKey(key);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 判断key是否存在
     * @Param: key:键
     * @return:布尔值
    com.laiYongBin.util.RedisTempUtil
     */
    public boolean delKey(String key){
        try {
            return redisTemplate.delete(key);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 缓存获取
     * @Param: [key]
    com.laiYongBin.util.RedisTempUtil
     */
    public Object get(String key){
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * @Description: 缓存放入
     * @Param: [key, value]
    com.laiYongBin.util.RedisTempUtil
     */
    public boolean set(String key, Object value){
        try{
            redisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 放入缓存并设置过期时间,若是时间<=0,则是永久
            * @Param: [key, value, time]
            com.laiYongBin.util.RedisTempUtil
     */
    public boolean set(String key, Object value, long time){
        try{
            if (time>0){
                redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
            }else {
                set(key,value);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}

